import type {
  BackgroundImageConfig,
  CustomConfig,
  FullPlatformConfig,
  ItemStateCollection,
  PlatformElementConfig,
  PlatformTypeValue,
} from '../interfaces'
import {
  BASE_COLORS,
  SYMBOLS,
} from '../interfaces'
import { FIVE_ONE_CTO_FRAMEWORK_CONFIG } from './personalization/51_cto'
import { BAI_DU_FRAMEWORK_CONFIG } from './personalization/bai_du'
import { BIAN_FRAMEWORK_CONFIG } from './personalization/bian'
import { BILIBILI_FRAMEWORK_CONFIG } from './personalization/bilibili'
import { BILIBILI_VIDEO_FRAMEWORK_CONFIG } from './personalization/bilibili_video'
import { BING_FRAMEWORK_CONFIG } from './personalization/bing'
import { IMAGE_PRIORITY } from './personalization/common'
import { CSDN_FRAMEWORK_CONFIG } from './personalization/csdn'
import { GITEE_FRAMEWORK_CONFIG } from './personalization/gitee'
import { GITHUB_FRAMEWORK_CONFIG } from './personalization/github'
import { GOOGLE_FRAMEWORK_CONFIG } from './personalization/google'
import { GREASY_FORK_FRAMEWORK_CONFIG } from './personalization/greasy_fork'
import { ICONFONT_FRAMEWORK_CONFIG } from './personalization/iconfont'
import { JIAN_SHU_FRAMEWORK_CONFIG } from './personalization/jian_shu'
import { JUE_JIN_FRAMEWORK_CONFIG } from './personalization/jue_jin'
import { SO_FRAMEWORK_CONFIG } from './personalization/so'
import { SOGOU_FRAMEWORK_CONFIG } from './personalization/sogou'
import { ZHI_HU_FRAMEWORK_CONFIG } from './personalization/zhi_hu'
import { ZHI_HU_QUESTION_FRAMEWORK_CONFIG } from './personalization/zhi_hu_question'
import { SUPPORTED_PLATFORMS } from './platform'

/**
 * 预处理元素配置，生成完整的选择器路径
 */
export function preprocessElementConfigs(
  elements: Record<string, PlatformElementConfig>,
): Record<string, PlatformElementConfig> {
  const elementMap = new Map<string, PlatformElementConfig>()
  const result: Record<string, PlatformElementConfig> = {}

  // 首先将所有元素存入map方便查找
  Object.values(elements).forEach((element) => {
    elementMap.set(element.id, element)
  })

  // 处理每个元素
  Object.entries(elements).forEach(([key, config]) => {
    if (config.inherit && config.category) {
      // 处理继承关系
      const fullSelector = buildInheritedSelector(config.id, elementMap)
      result[key] = {
        ...config,
        selector: fullSelector, // 替换为完整的继承选择器
      }
    }
    else {
      result[key] = config
    }
  })

  return result
}

/**
 * 递归构建继承的选择器路径
 */
function buildInheritedSelector(
  elementId: string,
  elementMap: Map<string, PlatformElementConfig>,
  visited: Set<string> = new Set(), // 防止循环引用
): string {
  const element = elementMap.get(elementId)
  if (!element)
    return ''

  // 防止循环引用
  if (visited.has(elementId)) {
    return element.selector
  }
  visited.add(elementId)

  // 基础选择器
  let selector = element.selector

  // 如果有继承关系且存在父级
  if (element.inherit && element.category) {
    const parentSelector = buildInheritedSelector(element.category, elementMap, visited)
    if (parentSelector) {
      selector = `${parentSelector} ${selector}`
    }
  }

  return selector
}

/**
 * 个性化设置项状态
 */
export const ITEM_STATE: ItemStateCollection = {
  SAVED: {
    key: 'saved',
    attributes: 'data-saved',
    suffix: 'status:saved',
    className: 'saved',
    symbol: SYMBOLS.COLOR_CIRCLES.GREEN,
    color: BASE_COLORS.SUCCESS,
  },
  CHANGED: {
    key: 'changed',
    attributes: 'data-changed',
    suffix: 'status:changed',
    className: 'changed',
    symbol: SYMBOLS.COLOR_CIRCLES.YELLOW,
    color: BASE_COLORS.WARNING,
  },
  INVALID: {
    key: 'invalid',
    className: 'invalid',
    symbol: SYMBOLS.COLOR_CIRCLES.RED,
    color: BASE_COLORS.ERROR,
  },
  SKIPPED: {
    key: 'skipped',
    className: 'skipped',
    symbol: SYMBOLS.COLOR_CIRCLES.PURPLE,
    color: BASE_COLORS.TEXT_SECONDARY,
  },
}

/**
 * 个性化设置存储配置
 * 1）顺序要求，第一个为值，第二个为模式，第三个为扩展...
 */
export const PERSONALIZATION_STORAGE_CONFIG: Record<string, Array<string>> = {
  BackgroundImage: ['value', 'bg-image-mode'],
  CustomCss: ['value', 'custom-css-mode', 'custom-css-url-content'],
  CustomJs: ['value', 'custom-js-mode', 'custom-js-url-content'],
}

/**
 * 页面类型
 */
export const PLATFORM_PAGE_TYPES = {
  BLOG: {
    value: 'blog',
    framework: {
      GLOBAL: 'global',
      WRAPPER: 'wrapper',
      TITLE: 'title',
      META: 'meta',
      CONTENT: 'content',
    },
  },
  TIEBAR: {
    value: 'tiebar',
    framework: {
      GLOBAL: 'global',
      WRAPPER: 'wrapper',
      TITLE: 'title',
      META: 'meta',
      CONTENT: 'content',
    },
  },
  SEARCH: {
    value: 'search',
    framework: {
      GLOBAL: 'global',
      INPUT: 'input',
      RESULTS: 'results',
    },
  },
  VIDEO: {
    value: 'video',
    framework: {
      GLOBAL: 'global',
      PLAYER: 'player',
    },
  },
  OTHERS: {
    value: 'others',
    framework: {},
  },
}
/**
 * 默认背景图片配置
 */
const DEFAULT_BACKGROUND_IMAGE_CONFIG: BackgroundImageConfig = {
  enabled: true,
  id: 'background-image',
  category: 'base-settings',
  categoryKey: 'category',
  priority: IMAGE_PRIORITY,
  styleVar: '--page-background-image',
  wallpaper: {
    enabled: true,
  },
}

/**
 * 简书背景图片配置
 */
const JIAN_SHU_BACKGROUND_IMAGE_CONFIG: BackgroundImageConfig = {
  enabled: true,
  id: 'background-image',
  category: 'base-settings',
  categoryKey: 'category',
  priority: IMAGE_PRIORITY,
  styleVar: '--page-background-image',
  wallpaper: {
    enabled: true,
    zIndex: 0,
  },
}

const DEFAULT_CUSTOM_CSS_CONFIG: CustomConfig = {
  id: 'custom-css',
  category: 'custom-code',
  categoryKey: 'category',
  priority: 200,
  styleVar: '--page-custom-css',
}

const DEFAULT_CUSTOM_JS_CONFIG: CustomConfig = {
  id: 'custom-js',
  category: 'custom-code',
  categoryKey: 'category',
  priority: 200,
  styleVar: '--page-custom-js',
}

export const PlatformConfigs: Record<PlatformTypeValue, FullPlatformConfig> = {
  [SUPPORTED_PLATFORMS.CSDN]: {
    type: 'blog',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: CSDN_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.ZHI_HU]: {
    type: 'blog',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: ZHI_HU_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.JIAN_SHU]: {
    type: 'blog',
    global: {
      defaults: {
        backgroundImage: JIAN_SHU_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: JIAN_SHU_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.JUE_JIN]: {
    type: 'blog',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: JUE_JIN_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.FIVE_ONE_CTO]: {
    type: 'blog',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: FIVE_ONE_CTO_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.ZHI_HU_QUESTION]: {
    type: 'tiebar',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: ZHI_HU_QUESTION_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.BAI_DU]: {
    type: 'search',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: BAI_DU_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.GOOGLE]: {
    type: 'search',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: GOOGLE_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.BING]: {
    type: 'search',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: BING_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.SO_GOU]: {
    type: 'search',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: SOGOU_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.SO]: {
    type: 'search',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: SO_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.BILIBILI_VIDEO]: {
    type: 'video',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: BILIBILI_VIDEO_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.BILIBILI]: {
    type: 'others',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: BILIBILI_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.GREASY_FORK]: {
    type: 'others',
    global: {
      defaults: {
        backgroundImage: DEFAULT_BACKGROUND_IMAGE_CONFIG,
        customCss: DEFAULT_CUSTOM_CSS_CONFIG,
        customJs: DEFAULT_CUSTOM_JS_CONFIG,
      },
    },
    contents: {
      framework: GREASY_FORK_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.ICONFONT]: {
    type: 'others',
    global: {
      defaults: {
      },
    },
    contents: {
      framework: ICONFONT_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.BIAN]: {
    type: 'others',
    global: {
      defaults: {
      },
    },
    contents: {
      framework: BIAN_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.GITEE]: {
    type: 'others',
    global: {
      defaults: {
      },
    },
    contents: {
      framework: GITEE_FRAMEWORK_CONFIG,
    },
  },
  [SUPPORTED_PLATFORMS.GITHUB]: {
    type: 'others',
    global: {
      defaults: {
      },
    },
    contents: {
      framework: GITHUB_FRAMEWORK_CONFIG,
    },
  },
}

export const CATEGORY_NAME_CONFIG = {
  // 设置元素
  'default': '常规设置',
  'custom-code': '定制脚本',
  'base-settings': '基础设置',
  'advanced-settings': '高级设置',
  'search-settings': '搜索设置',

  // ====================== blog  ======================
  // 公共页面元素
  'shortcuts': '快捷方式',
  'page-container': '页面内容',
  'page-theme': '页面主题',
  'page-loading': '页面加载',
  'page-elements': '页面元素',
  'article-image-custom': '文章图片（自定义）',
  'article-title-custom': '文章标题（自定义）',

  // 基础页面元素
  'main-container': '基础内容',
  'content-container': '主内容区',
  'meta-container': '文章元信息',
  'title-container': '标题容器',
  // 平台特色
  'activity-challenge': '活动挑战',
  // 文章元数据
  'info-container': '信息容器',
  'article-title': '文章标题',
  'article-author': '文章作者',
  'article-copyright-button': '文章版权按钮',
  'article-copyright-wrapper': '文章版权包裹',
  'article-tag': '文章标签',
  'resource-download': '资源下载',
  // 文章内容
  'article-container': '文章容器',
  'article-wrapper': '文章包裹',
  'article-content': '文章内容',
  'article-heading': '文章标题',
  'content-hr': '文章水平分隔线',
  'content-pre': '文章代码块',
  'content-code': '文章内联代码',
  'content-table': '文章表格',
  'content-mark': '文章标记',
  'content-link': '文章链接',
  'content-ul-li': '文章无序列表',
  'content-ol-li': '文章有序列表',
  'content-blockquote': '文章引用',

  // ====================== tiebar  ======================
  'question-container': '问题容器',
  'detail-wrapper': '详情包裹',
  'detail-container': '详情容器',
  'answers-container': '回答容器',
  'question-tags': '问题标签',
  'question-title': '问题标题',
  'question-progress': '问题进度',
  'answers-profile': '回答者头像',
  'answers-time': '回答时间',
  'shortcut-wrapper': '回答简述包裹',
  'answers-wrapper': '回答内容包裹',
  'answers-content': '回答内容',
  'answers-actions': '回答操作',

  // ====================== search  ======================
  // 基础页面元素
  'search-input': '搜索框',
  'search-results': '搜索结果',

  // ====================== video  ======================

  // ====================== others  ======================
  'header-container': '页眉容器',
  'result-container': '结果容器',
  'result-wrapper': '结果包裹',
  'pagination-container': '分页容器',
  // ====================== 油猴-通用页面 ======================
  'common-container': '反馈容器',
  // ====================== 油猴-反馈页面 ======================
  'feedback-content': '反馈内容',
}

export type categoryNameType = keyof typeof CATEGORY_NAME_CONFIG
